"use client";

import { useState, useEffect, useRef } from 'react';
import { useAuth } from '@/context/authContext';
import { get, post } from '@/lib/request';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { toast } from 'sonner';
import { Loader2, Camera } from 'lucide-react';

interface UserProfile {
  id: string;
  username: string;
  email: string;
  avatar: string | null;
  bio: string | null;
}

export default function ProfilePage() {
  const { setUser } = useAuth();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    async function fetchProfile() {
      try {
        const res = await get('/users/me');
        setProfile(res.data);
      } catch (error) {
        toast.error('加载个人信息失败');
      } finally {
        setLoading(false);
      }
    }
    fetchProfile();
  }, []);

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      // 构建data
      const formData = new FormData();
      formData.append('file', file);
      const uploadRes = await post('/uploading', formData);
      const { url: newAvatarUrl } = uploadRes.data;

      if (!newAvatarUrl) {
        throw new Error('文件上传失败');
      }
      // 2. 更新url
      const updateRes = await post('/users/me/avatar', { avatarUrl: newAvatarUrl });
      const updatedUser = updateRes.data;
      
      // 3. 更新profile
      setProfile(prev => prev ? { ...prev, avatar: updatedUser.avatar } : null);
      setUser(prev => prev ? { ...prev, avatar: updatedUser.avatar } : null);

      toast.success('头像更新成功！');
    } catch (error) {
      toast.error('头像更新失败');
    } finally {
      setUploading(false);
      // 重置
      if(fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-full">
        <Loader2 className="animate-spin text-gray-400" size={32} />
      </div>
    );
  }

  if (!profile) {
    return <div className="p-8 text-center text-red-500">无法加载个人信息。</div>;
  }

  return (
    <div className="p-6 md:p-10 max-w-2xl mx-auto">
      <header className="mb-8">
        <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200">个人中心</h1>
        <p className="text-gray-500 mt-1">管理你的个人信息和设置</p>
      </header>
      
      <section className="bg-white dark:bg-stone-800 p-6 rounded-lg shadow-sm">
        <div className="flex items-center space-x-6">
          <div className="relative group cursor-pointer" onClick={handleAvatarClick}>
            <Avatar className="h-24 w-24 border-4 border-white dark:border-stone-700 shadow-md">
              <AvatarImage src={profile.avatar || undefined} alt={profile.username} />
              <AvatarFallback className="text-3xl">
                {profile.username.charAt(0).toUpperCase()}
              </AvatarFallback>
            </Avatar>
            <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-40 flex justify-center items-center rounded-full transition-all duration-300">
              {uploading ? (
                <Loader2 className="animate-spin text-white" />
              ) : (
                <Camera className="text-white opacity-0 group-hover:opacity-100 transition-opacity" />
              )}
            </div>
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              className="hidden"
              accept="image/png, image/jpeg, image/gif"
              disabled={uploading}
            />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-200">{profile.username}</h2>
            <p className="text-gray-600 dark:text-gray-400">{profile.bio || '这个人很懒，什么都没留下...'}</p>
          </div>
        </div>
        
        <div className="mt-8 space-y-4">
          <div>
            <label className="text-sm font-medium text-gray-500">用户名</label>
            <p className="text-lg text-gray-800 dark:text-gray-200">{profile.username}</p>
          </div>
          <div>
            <label className="text-sm font-medium text-gray-500">用户ID</label>
            <p className="text-lg text-gray-800 dark:text-gray-200">{profile.id}</p>
          </div>
        </div>
      </section>
    </div>
  );
} 